package com.fancy.learncenter.common;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;


import com.fancy.learncenter.utils.ToastUtil;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Hyy on 2016/12/1.
 */

public class AudioPlayer implements MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener {
    private Context mContext;
    public MediaPlayer mediaPlayer;
    private SeekBar skbProgress;
    private Timer mTimer = new Timer();
    private String videoUrl;
    private boolean pause;
    private int playPosition;
    private ProgressBar audioProgressBar;
    private TextView playTimeTxt;
    private TextView totalTimeTxt;
    private static final String TAG = "AudioPlayer";

    public AudioPlayer(Context context, SeekBar skbProgress, String videoUrl, TextView playTimeTxt, TextView totalTimeTxt) {
        this.mContext = context;
        this.skbProgress = skbProgress;
        this.videoUrl = videoUrl;
        this.playTimeTxt = playTimeTxt;
        this.totalTimeTxt = totalTimeTxt;
        init();
    }

    public AudioPlayer(Context context) {
        this.mContext = context;
        init();
    }

    public AudioPlayer(Context context, String videoUrl, ProgressBar audioProgressBar, TextView playTimeTxt, TextView totalTimeTxt) {
        this.mContext = context;
        this.videoUrl = videoUrl;
        this.audioProgressBar = audioProgressBar;
        this.playTimeTxt = playTimeTxt;
        this.totalTimeTxt = totalTimeTxt;
        init();
    }

    public AudioPlayer(Context context, String videoUrl) {
        this.mContext = context;
        this.videoUrl = videoUrl;
        init();
    }


    private void init() {
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnBufferingUpdateListener(this);
            mediaPlayer.setOnPreparedListener(this);
        } catch (Exception e) {
            Log.e(TAG, "error", e);
        }
        mTimer.schedule(mTimerTask, 0, 1000);
    }

    TimerTask mTimerTask = new TimerTask() {
        @Override
        public void run() {
            if (mediaPlayer == null)
                return;
            if (skbProgress != null) {
                if (mediaPlayer.isPlaying() && skbProgress.isPressed() == false) {
                    handleProgress.sendEmptyMessage(0);
                }
            } else {
                if (mediaPlayer.isPlaying()) {
                    handleProgress.sendEmptyMessage(0);
                }
            }

        }
    };

    Handler handleProgress = new Handler() {
        public void handleMessage(Message msg) {
            if (mediaPlayer != null) {
                int position = mediaPlayer.getCurrentPosition();
                int duration = mediaPlayer.getDuration();
                String playTime = formatPlayTime(Long.valueOf(position));
                if (playTimeTxt != null) {
                    playTimeTxt.setText(playTime);
                }
                if (skbProgress != null && duration > 0) {
                    long pos = skbProgress.getMax() * position / duration;
                    skbProgress.setProgress((int) pos);
                }
            }
        }
    };

    private String formatPlayTime(Long time) {
        DateFormat formatter = new SimpleDateFormat("mm:ss");
        return formatter.format(new Date(time));
    }

    public void callIsComing() {
        if (mediaPlayer.isPlaying()) {
            playPosition = mediaPlayer.getCurrentPosition();
            mediaPlayer.stop();
        }
    }

    public void callIsDown() {
        if (playPosition > 0) {
            playAudio(playPosition);
            playPosition = 0;
        }
    }

    public void play() {
        playAudio(0);
    }

    public void replay() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.seekTo(0);
        } else {
            playAudio(0);
        }
    }

    public boolean pause() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            pause = true;
        } else {
            if (pause) {
                mediaPlayer.start();
                pause = false;
            }
        }
        return pause;
    }

    public void stopRadio() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
    }

    public void stop() {
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    @Override
    public void onPrepared(MediaPlayer arg0) {
        arg0.start();
        Log.e(TAG, "onPrepared");
    }

    @Override
    public void onCompletion(MediaPlayer arg0) {
        Log.e(TAG, "onCompletion");
    }

    @Override
    public void onBufferingUpdate(MediaPlayer arg0, int bufferingProgress) {
        if (skbProgress != null) {
            skbProgress.setSecondaryProgress(bufferingProgress);
        }
    }

    private void playAudio(int playPosition) {
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(videoUrl);
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MyPreparedListener(playPosition));
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(final MediaPlayer mp, final int what,
                                       final int extra) {

                    ToastUtil.show("无法播放此音频文件");
                    if (audioProgressBar != null) {
                        audioProgressBar.setVisibility(View.GONE);
                    }
                    return false;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setDataSource(String videoUrl) {

        try {
            this.videoUrl = videoUrl;
            mediaPlayer.reset();
            mediaPlayer.setDataSource(videoUrl);
            mediaPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private final class MyPreparedListener implements MediaPlayer.OnPreparedListener {
        private int playPosition;

        public MyPreparedListener(int playPosition) {
            this.playPosition = playPosition;
        }

        @Override
        public void onPrepared(MediaPlayer mp) {
            mediaPlayer.start();
            if (audioProgressBar != null) {
                audioProgressBar.setVisibility(View.GONE);
            }
            if (mediaPlayer != null) {
                String totalTime = formatPlayTime(Long.valueOf(mediaPlayer.getDuration()));
                if (totalTimeTxt != null) {
                    totalTimeTxt.setText(totalTime);
                }
            }
            if (playPosition > 0) {
                mediaPlayer.seekTo(playPosition);
            }
        }
    }

}
